package com.jumi.microservice.service.taobao;

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jumi.microservice.constant.taobao.TaoBaoOrderStatusEnum;
import com.jumi.microservice.core.exception.BaseException;
import com.jumi.microservice.dto.taobao.TaoBaoOrder;
import com.jumi.microservice.entity.CouponOrder;
import com.jumi.microservice.entity.UserCoupon;
import com.jumi.microservice.mapper.CouponOrderMapper;
import com.jumi.microservice.mapper.UserCouponMapper;
import com.jumi.microservice.service.ITaoBaoAdminService;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Dirk
 * @Date 2021-01-14 09:18
 */
@DubboService
public class TaoBaoAdminServiceImpl implements ITaoBaoAdminService {

    private static Logger log = LoggerFactory.getLogger(ITaoBaoAdminService.class);

    @Resource
    private UserCouponMapper userCouponMapper;

    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Resource
    private CouponOrderMapper couponOrderMapper;

    @Resource
    private ProducerBean producerBean;

    @Override
    public void importOrderExcel(List<TaoBaoOrder> taoBaoOrderList) {
        if (ObjectUtils.isEmpty(taoBaoOrderList)) {
            throw new BaseException(500, "导入的淘宝订单为空");
        }
        log.info("导入的订单：[{}]", JSON.toJSONString(taoBaoOrderList));
        List<Long> tbSpecialIdList = taoBaoOrderList.stream().map(TaoBaoOrder::getTbSpecialId).collect(Collectors.toList());
        Map<Long, Long> tbSpecialIdUserMap = getUidByTbSpecialIds(tbSpecialIdList);
        List<CouponOrder> couponOrderList = new ArrayList<>();
        taoBaoOrderList.forEach(taoBaoOrder -> {
            CouponOrder couponOrder = new CouponOrder();
            Long uid = tbSpecialIdUserMap.getOrDefault(taoBaoOrder.getTbSpecialId(), 0L);
            if (uid.equals(0L)) {
                log.error("淘宝--导入的订单[{}]会员运营ID[{}]未找到对应的用户",
                        taoBaoOrder.getOrderSn(), taoBaoOrder.getTbSpecialId());
            }
            couponOrder.setUid(uid);
            couponOrder.setGoodsId(taoBaoOrder.getGoodsId());
            couponOrder.setGoodsTitle(taoBaoOrder.getGoodsTitle());
            couponOrder.setGoodsImage(taoBaoOrder.getGoodsImage());
            couponOrder.setGoodsPrice(taoBaoOrder.getGoodsPrice());
            couponOrder.setGoodsQuantity(taoBaoOrder.getGoodsQuantity());
            couponOrder.setOrderSn(taoBaoOrder.getOrderSn());
            TaoBaoOrderStatusEnum orderStatus = TaoBaoOrderStatusEnum.getByDesc(taoBaoOrder.getOrderStatusDesc());
            couponOrder.setCouponOrderStatus(orderStatus.getCode());
            couponOrder.setOrderStatus((byte) (orderStatus.ordinal() + 1));
            couponOrder.setOrderStatusDesc(taoBaoOrder.getOrderStatusDesc());
            couponOrder.setOrderTime(taoBaoOrder.getOrderTime());
            couponOrder.setPayAmount(taoBaoOrder.getPayAmount());
            couponOrder.setPayTime(taoBaoOrder.getPayTime());
            couponOrder.setSettlementAmount(taoBaoOrder.getSettlementAmount());
            couponOrder.setSettlementTime(taoBaoOrder.getSettlementTime());
            String promotionRateStr = taoBaoOrder.getPromotionRate();
            BigDecimal promotionRate = new BigDecimal(promotionRateStr.substring(0, promotionRateStr.indexOf("%")));
            couponOrder.setPromotionRate(promotionRate.divide(new BigDecimal("100"), 4, RoundingMode.FLOOR));
            couponOrder.setPromotionAmount(new BigDecimal(taoBaoOrder.getPromotionAmount()));
            couponOrder.setPromotionId(taoBaoOrder.getPromotionId());
            couponOrder.setPromotionName(taoBaoOrder.getPromotionName());
            couponOrder.setTbSpecialId(taoBaoOrder.getTbSpecialId());
            couponOrder.setSource(new Byte("1"));
            couponOrderList.add(couponOrder);
        });

        TaoBaoOrderHandler taoBaoOrderHandler = new TaoBaoOrderHandler(couponOrderList, couponOrderMapper, producerBean);
        threadPoolTaskExecutor.execute(taoBaoOrderHandler);
    }

    /**
     * 根据淘宝运营会员id获取用户uid
     *
     * @param tbSpecialIds
     * @return
     */
    private Map<Long, Long> getUidByTbSpecialIds(List<Long> tbSpecialIds) {
        if (ObjectUtils.isEmpty(tbSpecialIds)) {
            return new HashMap<>();
        }
        QueryWrapper<UserCoupon> userCouponQw = new QueryWrapper<>();
        userCouponQw.in("tb_special_id", tbSpecialIds);
        List<UserCoupon> userCouponList = userCouponMapper.selectList(userCouponQw);
        return userCouponList.stream().collect(Collectors.toMap(UserCoupon::getTbSpecialId, UserCoupon::getUid));
    }
}
